package com.itlong.cloud.intercept.sdkV1;

import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudTalkErrorCodeEnum;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <desc>
 *      云对讲SDK 请求身份验证拦截器
 * </desc>
 *
 * @createDate 2018/05/16
 */
@Aspect
@Component
public class CloudTalkSDKServerLoginIntercept {
    private static Logger LOG = LoggerFactory.getLogger(CloudTalkSDKServerLoginIntercept.class);

    @Value("${"+ PlatformConstants.CLOUD_TALK_SDK_SERVER_USER_TOKEN_DONTINTERCEPT+"}")
    String dontIntercept;   //不需要拦截的方法名

    @Value("${" + PlatformConstants.CLOUD_TALK_SDK_AESKEY + "}")
    private  String cloudTalkSdkAesKey; //AES加密KEY
    @Value("${" + PlatformConstants.CLOUD_TALK_SDK_MD5KEY + "}")
    private  String cloudTalkSdkMd5Key;  //MD5加密KEY

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller.sdkV1.cloud.intercom.server.*.*(..))")
    public void excudeService(){}

    /**
     * <desc>
     *     云对讲SDK APP身份验证拦截器
     * </desc>
     *
     * @param thisJoinPoint
     * @return
     * @author Jiaqi.X
     * @createDate 2018/05/16
     */
    //@Around("excudeService()") 此拦截器暂时不用
    public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint) throws Throwable{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String[] interceptMethod= StringHandlerUtil.splitString(dontIntercept);
        String uri = request.getRequestURI();
        if (uri.indexOf("error") > -1 || uri.indexOf("404") > -1) {   //屏蔽错误中继续错误的死循环
            return thisJoinPoint.proceed();
        }
        //获取拦截方法的所有属性
        MethodSignature signature = (MethodSignature) thisJoinPoint.getSignature();
        //循环配置不需要拦截的方法
        for(String method:interceptMethod){
            if(signature.getMethod().getName().equals(method)){
                return thisJoinPoint.proceed();
            }
        }
        String appId=request.getParameter("appId");
        PropertyUserInfoPO propertyUserInfoPO = iSDKUserServiceClient.getPropertyUserByAppId(appId);
            try {
                //解密
                String appSecret = request.getParameter("appSecret");
                //通过appId appSecret来进行服务认证
                if(StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(appSecret)){
                    if(iCloudTalkSDKServerUserServiceClient.sdkServerLogin(appId, appSecret)>0){
                        return thisJoinPoint.proceed();
                    }else{
                        return new MessageVO(CloudTalkErrorCodeEnum.SERVER_DEVELOP_ERR.getErrorCode());
                    }
                }else{
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
            }catch (Exception e){
                throw new DataAccessException("【云对讲SDK服务端】异常",e);

        }
    }

    /**
     * <desc>
     *      返回加密内容
     * </desc>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2018/04/10
     */
    /*private Map<String,Object> getEncryptResult(Object result,String cloudTalkSdkAesKey) throws Exception {
        MessageVO messageVO = (MessageVO)result;
        String encryptResult = DesEncryptUtil.aesEncryptNotMd5(JsonUtil.toJSON(messageVO), cloudTalkSdkAesKey);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("encryptScript", encryptResult);
        return resultMap;
    }*/
}
